import React, {Component} from 'react';
import SQLiteStorage from 'react-native-sqlite-storage';
import {ToastAndroid} from 'react-native';
SQLiteStorage.DEBUG(true);
var database_name = 'my_diary.db';
var database_version = '1.0';
var database_displayname = 'MySQLite';
var database_size = -1; //表示无限制
var db;
var checkExist;
export default class SQLite extends Component {
  constructor(props) {
    super(props);
    this.init();
  }
  init() {
    //初始化数据库
    if (!db) {
      this.open();
    }
    //检查表是否已存在
    if (!checkExist) {
      this.createTable();
    }
  }
  componentWillUnmount() {
    if (db) {
      this._successCB('close');
      db.close();
    } else {
      console.log('SQLiteStorage not open!');
    }
  }
  open() {
    db = SQLiteStorage.openDatabase(
      database_name,
      database_version,
      database_displayname,
      database_size,
      () => {
        this._successCB('open');
      },
      (err) => {
        this._errorCB('open', err);
      },
    );
    return db;
  }
  checkExist = () => {
    if (!db) {
      this.open();
    }
    this.executeSql(
      'select count(*) from sqlite_master where type = table and name = DIARY',
      [],
      (tx, results) => {
        var len = results.rows.length;
        console.log('是否存在:', len);
        if (len > 0) {
          return results.rows.item[0];
        } else {
          return 0;
        }
      },
      (err) => {
        return 0;
      },
    );
  };
  createTable() {
    if (!db) {
      this.open();
    }
    //创建记录表
    db.transaction(
      (tx) => {
        tx.executeSql(
          'CREATE TABLE IF NOT EXISTS DIARY(' +
            'id INTEGER PRIMARY KEY AUTOINCREMENT,' +
            'title VARCHAR,' +
            'content TEXT,' +
            'create_time DATETIME,' +
            'update_time DATETIME,' +
            'mood INT)',
          [],
          () => {
            this._successCB('createTable');
          },
          (err) => {
            this._errorCB('createTable', err);
          },
        );
      },
      (err) => {
        //所有的都应该有错误的回调方法，方便排查错误
        this._errorCB('transaction', err);
      },
      () => {
        this._successCB('transaction');
      },
    );
  }
  insertData(diary) {
    if (!db) {
      this.open();
    }
    db.transaction(
      (tx) => {
        let title = diary.title;
        let content = diary.body;
        let mood = diary.mood;
        let sql =
          'INSERT INTO DIARY(title,content,create_time,mood)' +
          'values(?,?,CURRENT_TIMESTAMP,?)';
        tx.executeSql(
          sql,
          [title, content, mood],
          () => {},
          (err) => {
            console.log(err);
          },
        );
      },
      (error) => {
        this._errorCB('transaction', error);
        ToastAndroid.show('数据插入失败', ToastAndroid.SHORT);
      },
      () => {
        this._successCB('transaction insert data');
        ToastAndroid.show('数据插入成功', ToastAndroid.SHORT);
      },
    );
  }
  updateData(dairy) {
    if (!db) {
      this.open();
    }
    db.transaction(
      (tx) => {
        let title = diary.title;
        let content = diary.body;
        let updateTime = diary.updateTime;
        let mood = diary.mood;
        let sql = 'UPDATE DIARY SET title = ?,content=?,update_time=?,mood=?';
        tx.executeSql(
          sql,
          [title, content, updateTime, mood],
          () => {},
          (err) => {
            console.log(err);
          },
        );
      },
      (error) => {
        this._errorCB('transaction', error);
        ToastAndroid.show('数据更新失败', ToastAndroid.SHORT);
      },
      () => {
        this._successCB('transaction insert data');
        ToastAndroid.show('数据更新成功', ToastAndroid.SHORT);
      },
    );
  }
  deleteData(id) {
    if (!db) {
      this.open();
    }
    db.transaction(
      (tx) => {
        let sql = 'DELETE FROM DIARY WHERE id = ?';
        tx.executeSql(
          sql,
          [id],
          () => {},
          (err) => {
            console.log(err);
          },
        );
      },
      (error) => {
        this._errorCB('transaction', error);
        ToastAndroid.show('数据删除失败', ToastAndroid.SHORT);
      },
      () => {
        this._successCB('transaction insert data');
        ToastAndroid.show('数据删除成功', ToastAndroid.SHORT);
      },
    );
  }
  _successCB(name) {
    console.log('SQLiteStorage ' + name + ' success');
  }
  _errorCB(name, err) {
    console.log('SQLiteStorage ' + name);
    console.log(err);
  }
  render() {
    return null;
  }
}
